//
//  KHHStoryAllPageViewController.m
//  Travel
//
//  Created by dllo on 15/11/30.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "KHHStoryAllPageViewController.h"
#import "KHHRecommendModel.h"
#import "KHHStoryItemCollectionViewCell.h"
#import "KHHStoryDetailPageViewController.h"
#import "CXNetHandle.h"
#import "MJRefresh.h"
#import "Story.h"
#import "CoreDataManager.h"

@interface KHHStoryAllPageViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *modelDataArr; //总数据数组
@property (nonatomic, retain)NSMutableArray *modelUserDataArr; //用户信息数组
@property (nonatomic, assign)NSInteger startID; //开始ID

@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain) NSMutableArray *arr_result;
@end

@implementation KHHStoryAllPageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [self selectAllLike];
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //当控制器上存在滑动视图时 给滑动视图添加上边距(0 , 64)
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"全部精选故事";
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"leftBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //初始化coredata单例
    self.manager = [CoreDataManager shareInstance];
    //获取数据
    [self getData];
    //创建view
    [self createView];
    //菊花
    [CXLoadMBProgress loadMBProgress:self.view];
    
}

#pragma mark - 获取数据
- (void)getData
{
    //查询数据库
    [self selectAllLike];
    
    //网络数据
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot/hot/list/?start=0"];
    [CXNetHandle getUrl:str cookie:nil result:^(id result) {
        
        //移除菊花
        [CXLoadMBProgress removeMBProgress:self.view];
        
        self.modelDataArr = [KHHRecommendModel transformWithArray:result[@"data"][@"hot_spot_list"]];
        
        NSMutableArray *userDataArr = [NSMutableArray array];
        for (NSDictionary *tempDic in result[@"data"][@"hot_spot_list"]) {
            [userDataArr addObject:tempDic[@"user"]];
        }
        self.modelUserDataArr = [KHHRecommendModel transformWithArray:userDataArr];
        
        [self.collectionView reloadData];
    }];
    
}

//查询数据库
- (void)selectAllLike
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Story" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    //*******谓词 /过滤数据 (注掉就查询所有)******
    //准确查询
    
   // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"index_title = %@", self.recommendModel.index_title];
    
    //[fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
    //排序 参数:根据什么排序 yes 升序  / no 降序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"index_title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    }
    [self.arr_result removeAllObjects];
    self.arr_result = [NSMutableArray arrayWithArray:fetchedObjects];
    
    [self.collectionView reloadData];
}


- (void)createView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(( [UIScreen mainScreen].bounds.size.width - 30) / 2, 240);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 0, 0, 0);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, -10, WIDTH, HEIGHT) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[KHHStoryItemCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
   // [[self class]BoolIsNight:self.collectionView];
    [self MJRefresh];
}

- (void)MJRefresh
{
    //MJ下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self getData];
    }];
    
    //上拉加载
    self.startID = 12;
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        
        NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot/hot/list/?start=%ld", self.startID];
        [CXNetHandle getUrl:str cookie:nil result:^(id result) {
            
            self.startID += 12;
            
            [self.modelDataArr addObjectsFromArray: [KHHRecommendModel transformWithArray:result[@"data"][@"hot_spot_list"]]];
            
            NSMutableArray *userDataArr = [NSMutableArray array];
            for (NSDictionary *tempDic in result[@"data"][@"hot_spot_list"]) {
                [userDataArr addObject:tempDic[@"user"]];
            }
            
            [self.modelUserDataArr addObjectsFromArray: [KHHRecommendModel transformWithArray:userDataArr]];
            
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
            
        }];
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.tag == 66) {
        return self.arr_result.count;
    } else {
        return self.modelDataArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KHHStoryItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    if (self.tag == 66) {
        cell.storyAllModel = self.arr_result[indexPath.item];
        cell.userModel = self.arr_result[indexPath.item];
        
    } else {
        
        cell.storyAllModel = self.modelDataArr[indexPath.item];
        cell.userModel = self.modelUserDataArr[indexPath.item];
    }
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    KHHStoryDetailPageViewController *storyDetail = [[KHHStoryDetailPageViewController alloc]init];
    if (self.tag == 66) {
        storyDetail.spot_id = [self.arr_result[indexPath.item] spot_id];
        
    } else {
        
        storyDetail.spot_id = ((KHHRecommendModel *)self.modelDataArr[indexPath.item]).spot_id;
    }
    storyDetail.hidesBottomBarWhenPushed = YES;
    //收藏
    storyDetail.recommendModel = self.modelDataArr[indexPath.item];
    storyDetail.userModel = self.modelUserDataArr[indexPath.item];
    [self.navigationController pushViewController:storyDetail animated:YES];
}

#pragma mark-滑动手势1
- (void)addScreenEdgePan
{
    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
    screenEdgePan.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:screenEdgePan];
    [self.collectionView addGestureRecognizer:screenEdgePan];
    
}
#pragma mark-滑动手势2
-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 自定义按钮触发方法 返回
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
